package org.test.jiazi_1.common.utils;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.TypeReference;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

public class IdCardAddressResolver {
    private static final Map<String, AddressInfo> ADDRESS_CODE_MAP = new HashMap<>();

    static {
        loadAddressData();
    }

    private static void loadAddressData() {
        try (InputStream is = IdCardAddressResolver.class.getClassLoader().getResourceAsStream("address_code.json")) {
            if (is == null) {
                throw new FileNotFoundException("地址码数据文件 address_code.json 未找到");
            }

            try (BufferedReader reader = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8))) {
                StringBuilder jsonContent = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    jsonContent.append(line);
                }

                Map<String, Map<String, Object>> topLevelMap = JSON.parseObject(
                        jsonContent.toString(),
                        new TypeReference<>() {
                        }
                );

                parseAddressData(topLevelMap);

                System.out.println("成功加载 " + ADDRESS_CODE_MAP.size() + " 个地址码");

            }
        } catch (Exception e) {
            throw new RuntimeException("加载地址码数据失败", e);
        }
    }

    private static void parseAddressData(Map<String, Map<String, Object>> topLevelMap) {
        for (Map.Entry<String, Map<String, Object>> provinceEntry : topLevelMap.entrySet()) {
            String[] provinceParts = provinceEntry.getKey().split("&");
            if (provinceParts.length != 2) {
                System.err.println("无效的省级数据格式: " + provinceEntry.getKey());
                continue;
            }

            String provinceName = provinceParts[0];
            String provinceCode = provinceParts[1];

            Map<String, Object> cityMap = provinceEntry.getValue();
            parseCityData(provinceName, cityMap);
        }
    }

    private static void parseCityData(String provinceName, Map<String, Object> cityMap) {
        for (Map.Entry<String, Object> cityEntry : cityMap.entrySet()) {
            String cityKey = cityEntry.getKey();

            String[] cityParts = cityKey.split("&");
            if (cityParts.length != 2) {
                System.err.println("无效的市级数据格式: " + cityKey);
                continue;
            }

            String cityName = cityParts[0];
            String cityCode = cityParts[1];

            // 只存储市级映射（前4位代码）
            // 例如：4510 -> 广西壮族自治区 百色市
            ADDRESS_CODE_MAP.put(cityCode.substring(0, 4), new AddressInfo(provinceName, cityName));

            // 对于县级代码，也映射到对应的市级
            Object cityValue = cityEntry.getValue();
            if (cityValue instanceof Map) {
                @SuppressWarnings("unchecked")
                Map<String, Object> countyMap = (Map<String, Object>) cityValue;
                mapCountiesToCity(provinceName, cityName, countyMap);
            }
        }
    }

    private static void mapCountiesToCity(String provinceName, String cityName, Map<String, Object> countyMap) {
        for (String countyKey : countyMap.keySet()) {
            String[] countyParts = countyKey.split("&");
            if (countyParts.length != 2) {
                continue;
            }

            String countyCode = countyParts[1];
            // 将县级代码也映射到对应的省市信息
            // 例如：451021 -> 广西壮族自治区 百色市
            ADDRESS_CODE_MAP.put(countyCode, new AddressInfo(provinceName, cityName));
        }
    }

    public static class AddressInfo {
        private final String province;
        private final String city;

        public AddressInfo(String province, String city) {
            this.province = province;
            this.city = city;
        }

        public String getProvince() { return province; }
        public String getCity() { return city; }

        @Override
        public String toString() {
            return province + city;
        }

        // 获取省份
        public String getProvinceOnly() {
            return province;
        }

        // 获取城市
        public String getCityOnly() {
            return city;
        }
    }

    /**
     * 根据身份证号解析省市信息
     * @param idCard 18位身份证号
     * @return 省市信息对象，只包含省和市
     */
    public static AddressInfo resolveProvinceCity(String idCard) {
        if (idCard == null || idCard.length() != 18) {
            System.out.println("无效的身份证号");
            return null;
        }

        String addressCode = idCard.substring(0, 6);

        // 直接查找6位地址码对应的省市信息
        AddressInfo addressInfo = ADDRESS_CODE_MAP.get(addressCode);
        if (addressInfo != null) {
            return addressInfo;
        }

        // 如果找不到，尝试用前4位查找市级信息
        addressInfo = ADDRESS_CODE_MAP.get(addressCode.substring(0, 4));
        if (addressInfo != null) {
            return addressInfo;
        }

        System.out.println("未找到对应的地址码: " + addressCode);
        return null;
    }

    /**
     * 获取完整的省市地址字符串
     * @param idCard 18位身份证号
     * @return 省市地址字符串，如"广西壮族自治区 百色市"
     */
    public static String getProvinceCityAddress(String idCard) {
        AddressInfo info = resolveProvinceCity(idCard);
        return info != null ? info.toString() : "未知地址";
    }

    /**
     * 只获取省份名称
     * @param idCard 18位身份证号
     * @return 省份名称
     */
    public static String getProvince(String idCard) {
        AddressInfo info = resolveProvinceCity(idCard);
        return info != null ? info.getProvinceOnly() : "未知省份";
    }

    /**
     * 只获取城市名称
     * @param idCard 18位身份证号
     * @return 城市名称
     */
    public static String getCity(String idCard) {
        AddressInfo info = resolveProvinceCity(idCard);
        return info != null ? info.getCityOnly() : "未知城市";
    }

    // 测试方法
    public static void main(String[] args) {
        // 测试用例
        String[] testIds = {
                "451021199001011234", // 广西百色市田阳县 → 广西壮族自治区 百色市
                "451000199001011234", // 广西百色市 → 广西壮族自治区 百色市
                "451100199001011234", // 广西贺州市 → 广西壮族自治区 贺州市
                "110101199001011234", // 北京市东城区 → 北京市 东城区
                "123456789012345678"  // 无效地址码
        };
                System.out.println("省市地址: " + getProvinceCityAddress("451000199001011234"));
        for (String idCard : testIds) {
            System.out.println("身份证: " + idCard);
            AddressInfo info = resolveProvinceCity(idCard);
            if (info != null) {
                System.out.println("省市地址: " + info.toString());
                System.out.println("省份: " + info.getProvinceOnly());
                System.out.println("城市: " + info.getCityOnly());
            } else {
                System.out.println("解析失败");
            }
            System.out.println("---");
        }
    }
}